package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Session.UnsubscribeReq;
import net.ib.mntalk.protocol.Session.UnsubscribeRes;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.clientapi.DeliverMessages;
import net.ib.mtalk.util.GpbSupport;
import android.content.Context;

/**
 * COMMENT : 채팅창에서 나갈 때, 현재의 채팅창으로 등록한 subscribe를 철회한다<br>
 * PRE-EXECUTE : 현재 뷰 UUID로 철회 신청함<br>
 * POST-EXECUTE : DeliverMessage.callback을 null로 세팅함(만약 서버에서 응답이 없거나 실패가 떨어져도 메시지를 받으면 안되므로)<br>
 * @author eugenel
 *
 */
public class UnsubscribeTask extends AsyncNetTask {
	
	private long mClientViewMsb;
	private long mClientViewLsb;

	public UnsubscribeTask(Context _context, long clientViewMsb, long clientViewLsb) {
		super(_context);
		mClientViewMsb = clientViewMsb;
		mClientViewLsb = clientViewLsb;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		UnsubscribeReq unsubscribeReq = new UnsubscribeReq();
		unsubscribeReq.setViewUuid(InboxDatabaseHelper.getViewUUID(mContext, mClientViewMsb, mClientViewLsb));
		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(unsubscribeReq)
			.setMethodId(Session.Messaging.Unsubscribe)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object requestObj, Object resultObj) {
		if (resultObj == null) {
			return;	// do nothing
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) resultObj;
		UnsubscribeRes res = (UnsubscribeRes) resultEnvelope.getMessage();
		
		//if (res.getResponseCode() == Common.SUCCESS) {
		DeliverMessages.setCallback(null);
		// TODO 만약 실패 시, 우리쪽 callback은 해제하지만 서버에 다시 요청해야 하는지 
		// 서버팀에 문의
		//}
	}

}
